package com.qdu.controller;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.PostConstruct;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qdu.service.SocketService;

@Component
@ServerEndpoint("/socket/asset")
public class WebSocket {

	
	@PostConstruct
	public void init() {
		
		System.out.println("websocket 加载");
	}
	private static Logger log = LoggerFactory.getLogger(WebSocket.class);
	private static final AtomicInteger OnlineCount = new AtomicInteger(0);
	// concurrent包的线程安全Set，用来存放每个客户端对应的Session对象。
	private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
	public static SocketService service;
	private static ObjectMapper JSON = new ObjectMapper();
	/**
	 * 连接建立成功调用的方法
	 */
	@OnOpen
	public void onOpen(Session session) {

		SessionSet.add(session);
		int cnt = OnlineCount.incrementAndGet(); // 在线数加1
		log.info("连接打开:当前连接数：{}", cnt);
		System.out.println(service.totalBussiness());
		SendMessage(service.getAllData(""));
	}

	/**
	 * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
	 * 
	 * @param session
	 * @param message
	 */
	public static void SendMessage(Object message) {
		for (Session session : SessionSet) {
			try {
				if (session.isOpen()) {
					session.getBasicRemote()
							.sendText(JSON.writeValueAsString(message));
				}
			} catch (IOException e) {
				log.error("发送消息出错：{}", e.getMessage());
				e.printStackTrace();
			}
		}
	}

	public static void SendTextMessage(Object message) {
		for (Session session : SessionSet) {
			try {
				if (session.isOpen()) {
					session.getBasicRemote()
							.sendText(JSON.writeValueAsString(message));
				}
			} catch (IOException e) {
				log.error("发送消息出错：{}", e.getMessage());
				e.printStackTrace();
			}
		}
	}
	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose(Session session) {
		SessionSet.remove(session);
		int cnt = OnlineCount.decrementAndGet();
		log.info("有连接关闭，当前连接数为：{}", cnt);
	}

	/**
	 * 收到客户端消息后调用的方法
	 *
	 * @param message 客户端发送过来的消息
	 */
	@OnMessage
	public void onMessage(String message, Session session) {
		log.info("来自客户端的消息：{}", message);
		SendMessage(service.getAllData("ss"));
		
	}

	/**
	 * 出现错误
	 * 
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Throwable error) {
		log.error("发生错误：{}，", error.getMessage());
		error.printStackTrace();
	}


}
